package org.samith.web.servlet;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.samith.dao.UserDao;
import org.samith.entity.User;
import org.samith.web.helper.WebUtil;

public class ForgotPasswordServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	@EJB
	UserDao userDao;
	
	public void init() throws ServletException {
		super.init();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ServletContext context = getServletConfig().getServletContext();
		context.getRequestDispatcher("/ForgotPassword/index.jsp").forward(request,
				response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String login = request.getParameter("userName");
		User user = userDao.findByUserName(login);
		if(user != null){
			String code = WebUtil.generatePseudoRandomString();
			user.setPasswordResetCode(code);
			userDao.update(user);
			response.sendRedirect("/ejbApp/forgotPasswordReset");
		}else{
			System.out.println("========= No user found with this username =================");
			doGet(request, response);
		}
	}
}